import { createRouter, createWebHistory } from 'vue-router'
import Dashboard from '@/views/dashboard/Dashboard.vue'
import Home from '@/views/Home.vue'
import { useProfileStore } from '@/store/profile'

export const routes = [
  {
    path: '/',
    name: 'home',
    component: Home,
    children: [
      { path: '', name: 'home-default', component: () => import('@/views/dashboard/Found.vue') },
      { path: 'found', name: 'found', component: () => import('@/views/dashboard/Found.vue') },
      { path: 'inform', name: 'inform', component: () => import('@/views/dashboard/Inform.vue') },
      {
        path: 'promotion',
        name: 'promotion',
        component: () => import('@/views/dashboard/Promotion.vue'),
      },
      {
        path: 'shoppingcart',
        name: 'shoppingcart',
        component: () => import('@/views/dashboard/ShoppingCart.vue'),
      },
      {
        path: 'profile',
        name: 'profile',
        component: () => import('@/views/dashboard/Profile.vue'),
      },
      { path: 'trends', name: 'trends', component: () => import('@/views/dashboard/Trends.vue') },
      { path: 'search', name: 'search', component: () => import('@/views/dashboard/Search.vue') },
      { path: 'item/:id', name: 'item', component: () => import('@/views/dashboard/Item.vue') },
      { path: 'order', name: 'order', component: () => import('@/views/dashboard/Order.vue') },
      {
        path: 'success',
        name: 'success',
        component: () => import('@/views/dashboard/PaySuccess.vue'),
      },
      {
        path: 'payment',
        name: 'payment',
        component: () => import('@/views/dashboard/Payment.vue'),
      },
    ],
  },
  { path: '/dashboard', name: 'dashboard', component: Dashboard },
  { path: '/notFound', name: 'NotFound', component: () => import('../views/404.vue') },
  { path: '/:pathMatch(.*)', redirect: '/notFound' },
]

const router = createRouter({
  scrollBehavior: (): { left: number; top: number } => ({ left: 0, top: 0 }),
  history: createWebHistory(),
  routes,
})

//全局前置守卫，每次路由切换时都会出发。
//_to 表示目标路由，_from 表示当前离开的路由，next() 表示允许导航继续。
router.beforeEach((_to, _from, next) => {
  next()
  //当前代码中没有实际逻辑，仅作为占位符，可以用来添加权限验证等功能。
  const profileStore = useProfileStore()
  if (!profileStore.isLoggedIn && _to.path !== '/') {
    // 如果未登录且不是前往首页，可以在此处添加处理逻辑
    // 但不要阻止导航，因为我们要让登录弹窗在任何页面都能显示
  }
})

//将创建的路由实例导出，供其他文件（如主应用 main.ts）使用，以集成到 Vue 应用中。
export default router
